package org.framework.RmPartyTypeByHUI;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quickbundle.base.web.page.RmPageVo;
import org.quickbundle.orgauth.rmfunctionnode.vo.RmFunctionNodeVo;
import org.quickbundle.orgauth.rmpartytype.service.IRmPartyTypeService;
import org.quickbundle.orgauth.rmpartytype.util.IRmPartyTypeConstants;
import org.quickbundle.orgauth.rmpartytype.vo.RmPartyTypeVo;
import org.quickbundle.project.IGlobalConstants;
import org.quickbundle.project.RmGlobalReference;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.cache.RmSqlCountCache;
import org.quickbundle.tools.helper.RmJspHelper;
import org.quickbundle.tools.helper.RmPopulateHelper;
import org.quickbundle.tools.helper.RmSqlHelper;
import org.quickbundle.tools.helper.RmVoHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dfhc.ISystemConstant;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentLockException;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentRoute;
import com.dfhc.util.CsrfHelper;
import com.dfhc.util.FileOperateHelper;
import com.dfhc.util.HttpClientUtil;
import com.dfhc.util.JspHelper;
import com.dfhc.util.StringHelper;
import com.dfhc.util.XssHelper;


@Controller
@RequestMapping(value = "/RmPartyTypeByHUI")
public class RmPartyTypeByHUIController implements IRmPartyTypeConstants {
	/*
	 * 团体类型模块服务
	 * 
	 * */
	@Autowired
	
	private IRmPartyTypeService iRmPartyTypeService;
	
	/**
     * 简单查询，分页显示，支持表单回写
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "")
    public String list(Model model, HttpServletRequest request) {
    	request.setAttribute(REQUEST_QUERY_CONDITION, "");
          String queryCondition = getQueryCondition(request);  //从request中获得查询条件
          RmPageVo pageVo = RmJspHelper.transctPageVo(request, getCount(queryCondition));
          String orderStr = RmJspHelper.getOrderStr(request);  //得到排序信息
          List<RmPartyTypeVo> beans = iRmPartyTypeService.queryByCondition(queryCondition, orderStr, pageVo.getStartIndex(), pageVo.getPageSize());  //按条件查询全部,带排序
          //如果采用下边这句，就是不带翻页的，同时需要删掉list页面的page.jsp相关语句
          //beans = service.queryByCondition(queryCondition, orderStr);  //查询全部,带排序
          RmJspHelper.saveOrderStr(orderStr, request);  //保存排序信息
          request.setAttribute(REQUEST_QUERY_CONDITION, queryCondition);
          request.setAttribute(REQUEST_BEANS, beans);  //把结果集放入request
          request.setAttribute(REQUEST_WRITE_BACK_FORM_VALUES, RmVoHelper.getMapFromRequest((HttpServletRequest) request));  //回写表单
          return "/qb5activiti/rmPartyType/listRmPartyTypeByHUI";
    }
    /**
     * ajax 请求列表数据
     * @param model
     * @param request
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "ajaxList",  produces="application/json")
    @ResponseBody
    public Map<String,Object> ajaxList(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException{
           boolean bLock = false;
           Map<String,Object> dataMap=new HashMap<String,Object>();
           try{
		        XssHelper.check(request,null);//校验请求数据是否含XSS攻击"关键字"
		        bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
		        //获取开始记录数
		        String startRow = request.getParameter(ISystemConstant.PAGE_START_KEY);
		        String rows=request.getParameter(ISystemConstant.PAGE_SIZE_KEY)==null?ISystemConstant.DEFAULT_PAGE_SIZE:request.getParameter(ISystemConstant.PAGE_SIZE_KEY);	        
		        int rowsInt=Integer.parseInt(rows);//页大小
		        if(StringHelper.isEmpty(startRow)){
		        	startRow="0";
		        }
		        int startRowInt = Integer.parseInt(startRow);
		        Map<String, Object> searchPara= getQueryByCondition(request);
		        String searchParam = getQueryCondition(request);  //从request中获得查询条件
		        String queryCondition = getQueryCondition(request);  //从request中获得查询条件
		        RmPageVo pageVo = RmJspHelper.transctPageVo(request, getCount(queryCondition));
		        String orderStr = RmJspHelper.getOrderStr(request);  //得到排序信息
		        int totalNum = iRmPartyTypeService.getRecordCount(searchParam);
	        
		        List<RmPartyTypeVo> beans = iRmPartyTypeService.queryByCondition(queryCondition, orderStr, pageVo.getStartIndex(), pageVo.getPageSize());  //按条件查询全部,带排序
	        	
		        //翻译状态码
	        	if(beans!=null){
	        	for(RmPartyTypeVo bean:beans){
				//如果状态码字段有其他用途，请用扩展字段attribute1-attribute5代替
	        	}
        	}         
	        	dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        dataMap.put(ISystemConstant.PAGE_DRAW, request.getParameter(ISystemConstant.PAGE_DRAW));
	        	dataMap.put(ISystemConstant.RECORDS_TOTAL,totalNum);
		        dataMap.put(ISystemConstant.RECORDS_FILTERED, totalNum);
	        	dataMap.put(ISystemConstant.DATA, beans);
	        	return dataMap;
          }catch(RequestConcurrentLockException e){
        	  RmProjectHelper.logInf(StringHelper.exceptionToString(e));
        	  dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
        	  dataMap.put(ISystemConstant.AJAX_MESSAGE, e.getMessage());
        	  return dataMap;   
          }catch(Exception e){
        	  e.printStackTrace();
        	  RmProjectHelper.logInf(StringHelper.exceptionToString(e));
        	  dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
        	  dataMap.put(ISystemConstant.AJAX_MESSAGE, "查询失败!");
        	  return dataMap;
          }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);	        
          }
    }
    /**
     * 跳转到新增页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "addPage")
    public String addPage(Model model, HttpServletRequest request) {    	            
          return "/qb5activiti/rmPartyType/addRmPartyTypeByHUI";
    }
    /**
     * 跳转到编辑和查看页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "showPage")
    public String showPage(Model model, HttpServletRequest request) {
          //获取id
          String id = request.getParameter(REQUEST_ID);
          //根据id查询定制项目模块
          if(!StringHelper.isEmpty(id)){
    		RmPartyTypeVo vo = iRmPartyTypeService.find(id);
    		model.addAttribute(REQUEST_BEAN, vo);
          }
          return "/qb5activiti/rmPartyType/addRmPartyTypeByHUI";
    }
    /*
     * 获取团体类型的总记录数
     * */
   private int getCount(String queryCondition) {
	   int count = RmSqlCountCache.getCount(TABLE_NAME, queryCondition);
   	if(count < 0) {
   		count = iRmPartyTypeService.getRecordCount(queryCondition);
   		RmSqlCountCache.putCount(TABLE_NAME, queryCondition, count);
   	}
   	return count;
	}
	/*
    * 业务查询条件
    * 
    * */
	private String getQueryCondition(HttpServletRequest request) {
		String queryCondition = null;
        if(request.getAttribute(REQUEST_QUERY_CONDITION) != null) {  //如果request.getAttribute中有，就不取request.getParameter
            queryCondition = request.getAttribute(REQUEST_QUERY_CONDITION).toString();
        } else {
			List<String> lQuery = new ArrayList<String>();
			
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".bs_keyword", request.getParameter("bs_keyword"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				try {
					if(request.getParameter("customerName")!=null){
					lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".name", new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8"), RmSqlHelper.TYPE_CHAR_LIKE));
					}else {
						lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".name", request.getParameter("name"), RmSqlHelper.TYPE_CHAR_LIKE));
					}
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".icon", request.getParameter("icon"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".description", request.getParameter("description"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".is_custom_attribute", request.getParameter("is_custom_attribute"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".is_allow_hanging_user", request.getParameter("is_allow_hanging_user"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".is_allow_hanging_role", request.getParameter("is_allow_hanging_role"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
				
			queryCondition = RmSqlHelper.appendQueryStr(lQuery.toArray(new String[0]));
        }
        return queryCondition;
	}
	/**
	 * 数据新增
	 * @param model
	 *            模型
	 * @param request
	 *            http请求对象
	 * @return 跳转的列表jsp
	 * @throws IOException
	 */
	@RequestMapping(value = "/insert")
	@ResponseBody
	public Map<String, Object> insert(Model model, HttpServletRequest request) throws IOException {
		boolean bLock = false;
		try {
			bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
			Map<String, Object> result = new HashMap<String, Object>();
			try {
				RmPartyTypeVo vo = new RmPartyTypeVo();
		        RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
		        RmVoHelper.markCreateStamp(request,vo);  //打创建时间,IP戳
		        
		        String id = iRmPartyTypeService.insert(vo);  //插入单条记录
		        request.setAttribute(IGlobalConstants.INSERT_FORM_ID, id);  //新增记录的id放入request属性
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
				result.put(ISystemConstant.AJAX_MESSAGE, "新增成功!");
			} catch (Exception e) {
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				result.put(ISystemConstant.AJAX_MESSAGE, "新增失败!");
			}
			return result;
		} finally {
			// 最后解锁
			RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
		}

	}
	/**
	 * 数据修改
	 * @param model
	 *            模型
	 * @param request
	 *            http请求对象
	 * @return 跳转的列表jsp
	 * @throws IOException
	 */
	@RequestMapping(value = "/update")
	@ResponseBody
	public Map<String, Object> update(Model model, HttpServletRequest request) throws IOException {
		boolean bLock = false;
		try {
			bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
			Map<String, Object> result = new HashMap<String, Object>();
			try {
				RmPartyTypeVo vo = new RmPartyTypeVo();
			    RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
			    RmVoHelper.markModifyStamp(request,vo);  //打修改时间,IP戳
			    int count = iRmPartyTypeService.update(vo);  //更新单条记录
			    request.setAttribute(EXECUTE_ROW_COUNT, count);  //sql影响的行数放入request属性
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
				result.put(ISystemConstant.AJAX_MESSAGE, "修改成功!");
			} catch (Exception e) {
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				result.put(ISystemConstant.AJAX_MESSAGE, "修改失败!");
			}
			return result;
		} finally {
			// 最后解锁
			RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
		}

	}
	/**
	 * 数据修改
	 * @param model
	 *            模型
	 * @param request
	 *            http请求对象
	 * @return 跳转的列表jsp
	 * @throws IOException
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(Model model, HttpServletRequest request) throws IOException {
		boolean bLock = false;
		try {
			bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
			Map<String, Object> result = new HashMap<String, Object>();
			try {
				int deleteCount = iRmPartyTypeService.delete(request.getParameter(REQUEST_ID));  //删除单条记录
			    request.setAttribute(EXECUTE_ROW_COUNT, deleteCount);  //sql影响的行数放入request属性
			    result.put(ISystemConstant.CSRF_CODE, CsrfHelper.getCsrfCode(request));
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
				result.put(ISystemConstant.AJAX_MESSAGE, "删除成功!");
			} catch (Exception e) {
				result.put(ISystemConstant.CSRF_CODE, CsrfHelper.getCsrfCode(request));
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				result.put(ISystemConstant.AJAX_MESSAGE, "删除失败!");
			}
			return result;
		} finally {
			// 最后解锁
			RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
		}
	}
	/**
	 * 简单查询，分页显示，支持表单回写
	 * 
	 * @param model
	 *            模型
	 * @param request
	 *            http请求对象
	 * @return 跳转的列表jsp
	 * @throws IOException
	 */
	@RequestMapping(value = "detail")
	public String detail(Model model, HttpServletRequest request) throws IOException {
		 RmPartyTypeVo bean = iRmPartyTypeService.find(request.getParameter(REQUEST_ID));  //通过id获取vo
	        request.setAttribute(REQUEST_BEAN, bean);  //把vo放入request
	        if(RM_YES.equals(request.getParameter(REQUEST_IS_READ_ONLY))) {
	            request.setAttribute(REQUEST_IS_READ_ONLY, request.getParameter(REQUEST_IS_READ_ONLY));
	        }
		return "/qb5activiti/rmPartyType/detailRmPartyTypeByHUI";
	}
	/**
     * 从request中获得查询条件
     * @param request http请求对象
     * @return 条件Map
     */
    public static Map<String, Object> getQueryByCondition(HttpServletRequest request) {
        Map<String, Object> searchMap = null;
        if(request.getAttribute(REQUEST_QUERY_CONDITION) != null) {  //如果request.getAttribute中有，就不取request.getParameter
            searchMap = (Map<String, Object>)request.getAttribute(REQUEST_QUERY_CONDITION);
        } else {
           searchMap = new HashMap<String, Object>();
           searchMap.put("id", request.getParameter("id"));
           try {
           	if(request.getParameter("bs_keyword")!=null){
           		String bs_keyword = new String(request.getParameter("bs_keyword").getBytes("ISO-8859-1"),"UTF-8");
           		searchMap.put("bs_keyword", bs_keyword);
           	}else{
           		searchMap.put("bs_keyword", request.getParameter("bs_keyword"));
           	}
   				} catch (UnsupportedEncodingException e) {
   					e.printStackTrace();
   			}
           searchMap.put("name", request.getParameter("name"));
           searchMap.put("icon", request.getParameter("icon"));
           searchMap.put("description", request.getParameter("description"));
           searchMap.put("is_custom_attribute", request.getParameter("is_custom_attribute"));
           searchMap.put("usable_status", ISystemConstant.DICTIONARY_RM_YES_NOT_1);
           searchMap.put("modify_date", request.getParameter("modify_date"));
           searchMap.put("modify_ip", request.getParameter("modify_ip"));
           searchMap.put("modify_user_id", request.getParameter("modify_user_id"));
           searchMap.put("is_allow_hanging_user", request.getParameter("is_allow_hanging_user"));
           searchMap.put("is_allow_hanging_role", request.getParameter("is_allow_hanging_role"));
           searchMap.put("searchName", request.getParameter(ISystemConstant.SEARCH_NAME));
        }
        return searchMap;
    }
}
